const http = require('http');
const fs = require('fs');
const artTemplate = require('art-template');
const api = require('url');

const comments = [];

http
    .createServer(function(req,res){
        var url = api.parse(req.url,true);
        var pathname = url.pathname;
        if(pathname === '/'){
            fs.readFile('./index.html',function(err,data){
                if(err) return res.end('404 No Found!');
                var html = artTemplate.render(data.toString(),{
                    comments: comments,
                });
                res.end(html);
            })
        }else if(pathname === '/pinglun'){
            //res.end(JSON.stringify(url.query));

            url.query.dataTime = new Date();
            comments.push(url.query);

            res.statusCode = 302;
            res.setHeader('Location','/');
            res.end();
        }else if(pathname === '/data'){
            res.writeHead(200, {
                'Content-Type': 'text/html;charset=UTF8'
            });
            res.end(JSON.stringify(comments));
        }else{
            res.end('地址输入有误，请确认后重新输入！');
        }
    })
    .listen(8889,function(){
        console.log('服务器启动成功，可以访问http://127.0.0.1:8889/...')
    })